import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class AddToCartServlet extends HttpServlet {
    private static final String UTF8 = "UTF-8";

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 获取商品信息
        String productId = request.getParameter("productId");
        String productName = request.getParameter("productName");
        String priceStr = request.getParameter("price");

        // 验证输入
        if (productId == null || productName == null || priceStr == null) {
            response.sendRedirect("index.html");
            return;
        }

        double price;
        try {
            price = Double.parseDouble(priceStr);
        } catch (NumberFormatException e) {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "价格格式无效");
            return;
        }

        // 获取或创建购物车Cookie
        Cookie cartCookie = getCartCookie(request);
        String cartJson;
        try {
            cartJson = URLDecoder.decode(cartCookie.getValue(), UTF8);
        } catch (UnsupportedEncodingException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "编码错误");
            return;
        }

        // 解析JSON购物车数据
        Gson gson = new Gson();
        Type cartType = new TypeToken<List<CartItem>>(){}.getType();
        List<CartItem> cartItems = gson.fromJson(cartJson, cartType);
        if (cartItems == null) {
            cartItems = new ArrayList<>();
        }

        // 查找商品是否已在购物车中
        boolean found = false;
        for (CartItem item : cartItems) {
            if (item.getProductId().equals(productId)) {
                item.setQuantity(item.getQuantity() + 1);
                found = true;
                break;
            }
        }

        // 如果商品不存在，添加到购物车
        if (!found) {
            cartItems.add(new CartItem(productId, productName, price, 1));
        }

        // 将购物车数据转换为JSON
        String newCartJson = gson.toJson(cartItems);

        // 更新Cookie值（URL编码）
        try {
            cartCookie.setValue(URLEncoder.encode(newCartJson, UTF8));
        } catch (UnsupportedEncodingException e) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "编码错误");
            return;
        }
        cartCookie.setMaxAge(30 * 24 * 60 * 60); // 30天有效期
        cartCookie.setPath("/");
        response.addCookie(cartCookie);

        // 重定向到购物车页面
        response.sendRedirect("view-cart");
    }

    private Cookie getCartCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("cart".equals(cookie.getName())) {
                    return cookie;
                }
            }
        }
        try {
            return new Cookie("cart", URLEncoder.encode("[]", UTF8));
        } catch (UnsupportedEncodingException e) {
            // 如果编码失败，返回空数组的原始JSON
            return new Cookie("cart", "[]");
        }
    }
}